/* USER CODE BEGIN Header */
/**
  ******************************************************************************
  * @file           : main.c
  * @brief          : Main program body
  ******************************************************************************
  * @attention
  *
  * Copyright (c) 2025 STMicroelectronics.
  * All rights reserved.
  *
  * This software is licensed under terms that can be found in the LICENSE file
  * in the root directory of this software component.
  * If no LICENSE file comes with this software, it is provided AS-IS.
  *
  ******************************************************************************
  */
/* USER CODE END Header */
/* Includes ------------------------------------------------------------------*/
#include "main.h"
#include "can.h"
#include "usart.h"
#include "gpio.h"

/* Private includes ----------------------------------------------------------*/
/* USER CODE BEGIN Includes */
#include "motor_manager.h" //电机管理层
#include "motion_planner.h"//运动规划层
#include <math.h>
#include <stdio.h>

/* USER CODE END Includes */

/* Private typedef -----------------------------------------------------------*/
/* USER CODE BEGIN PTD */

/* USER CODE END PTD */

/* Private define ------------------------------------------------------------*/
/* USER CODE BEGIN PD */

/* USER CODE END PD */

/* Private macro -------------------------------------------------------------*/
/* USER CODE BEGIN PM */

/* USER CODE END PM */

/* Private variables ---------------------------------------------------------*/

/* USER CODE BEGIN PV */
//电机ID定义
#define MOTOR_ID_1 0x07
Motor_Instance_t motor1;
Trapezoid_Planner_t planner1;
#define CONTROL_CYCLE_S 0.001f
#define ONE_REVOLUTION_RAD 6.2831853f //2*PI弧度
#define MAX_VEL_RAD_S      5.0f       // 设定一个合理的启动最大速度
#define ACCEL_RAD_S2       2.0f       // 设定一个合理的加速度
/* USER CODE END PV */

/* Private function prototypes -----------------------------------------------*/
void SystemClock_Config(void);
/* USER CODE BEGIN PFP */

/* USER CODE END PFP */

/* Private user code ---------------------------------------------------------*/
/* USER CODE BEGIN 0 */
/**
 * @brief 初始化 CAN 驱动，电机实例和规划器，并设置电机进入运行状态
 */
void Motor_System_Setup(void) {
  // 1. 底层 CAN 驱动激活（CubeMX 生成 MX_CAN1_Init() 之后调用）
  if (HAL_CAN_Start(&hcan1) != HAL_OK) {
    // 错误处理，CAN 启动失败
    Error_Handler();
  }
  // 2. 电机管理层初始化
  Motor_Manager_Init(&motor1, MOTOR_ID_1);

  // 3. 运动规划层初始化
  Planner_Init(&planner1);

  // 4. 电机控制流程（确保电机进入可控状态）
  // a. 停止电机 (确保安全切换模式)
  Motor_Manager_Stop(&motor1);
  HAL_Delay(50);

  // b. 设置为位置模式 (RUN_MODE_POSITION = 0x01)
  Motor_Manager_Set_Mode(&motor1, RUN_MODE_POSITION);
  HAL_Delay(50);

  // c. 使能电机 (准备接收控制指令)
  Motor_Manager_Enable(&motor1);
  HAL_Delay(50);

  // 此时 motor1.state = MOTOR_STATE_ENABLED
}
/**
 * @brief 周期性控制任务 (应在 CONTROL_CYCLE_S 频率下运行)
 */
void Control_Task_Execute(void) {

  // 2. 运动规划层 (计算目标值)
  // 根据 CONTROL_CYCLE_S 周期更新梯形轨迹，生成 pos_output 和 vel_output
  Planner_Update(&planner1, CONTROL_CYCLE_S);
  // 3. 应用目标值 (数据桥接)
  // 将 planner1 的输出赋值给 motor1 的 target_pos/target_vel
  Planner_Apply_To_Motor(&planner1, &motor1);
  // 4. 控制指令发送 (自顶向下指令流)
  // 根据 motor1.target_* 封装 CAN 帧，并调用 CAN 驱动发送 (Mode 1)
  Motor_Manager_Update_Control(&motor1);
}
int fputc(int ch, FILE *f)

{

  HAL_UART_Transmit(&huart1, (uint8_t *)&ch, 1, 0xffff);

  return ch;

}
/* USER CODE END 0 */

/**
  * @brief  The application entry point.
  * @retval int
  */
int main(void)
{

  /* USER CODE BEGIN 1 */

  /* USER CODE END 1 */

  /* MCU Configuration--------------------------------------------------------*/

  /* Reset of all peripherals, Initializes the Flash interface and the Systick. */
  HAL_Init();

  /* USER CODE BEGIN Init */

  /* USER CODE END Init */

  /* Configure the system clock */
  SystemClock_Config();

  /* USER CODE BEGIN SysInit */

  /* USER CODE END SysInit */

  /* Initialize all configured peripherals */
  MX_GPIO_Init();
  MX_CAN1_Init();
  MX_USART1_UART_Init();
  /* USER CODE BEGIN 2 */
  printf("Hello World\n");

  Motor_System_Setup();
  // 示例：启动第一次运动（假设从电机当前位置 motor1.feedback.pos_actual 开始）
  // 注意：在电机使能后，第一次反馈到达之前 motor1.feedback.pos_actual 可能为 0
  Planner_Start_Motion(&planner1,
                         ONE_REVOLUTION_RAD,          // 目标位置 6.28 rad (1 圈)
                         MAX_VEL_RAD_S,               // 最大速度
                         ACCEL_RAD_S2);               // 加速度
  /* USER CODE END 2 */

  /* Infinite loop */
  /* USER CODE BEGIN WHILE */
  while (1)
  {
    Control_Task_Execute();
    if (!planner1.is_planning && motor1.state == MOTOR_STATE_RUNNING) {
      // 如果规划完成，但电机还在运行状态

      // 确保目标值被设置为终点并保持静止
      motor1.target_pos = ONE_REVOLUTION_RAD;
      motor1.target_vel = 0.0f;

      // 可以选择将电机状态标记为 ENABLED 或 STOPPED，取决于后续控制逻辑
      // Motor_Manager_Stop(&motor1);

      // 假设我们只是让它停在终点位置，不再标记为运行状态
      motor1.state = MOTOR_STATE_ENABLED;

      // 此时，电机将停在 1 圈的位置 (6.28 rad)
    }
    HAL_Delay(1);
    /* USER CODE END WHILE */

    /* USER CODE BEGIN 3 */
  }
  /* USER CODE END 3 */
}

/**
  * @brief System Clock Configuration
  * @retval None
  */
void SystemClock_Config(void)
{
  RCC_OscInitTypeDef RCC_OscInitStruct = {0};
  RCC_ClkInitTypeDef RCC_ClkInitStruct = {0};

  /** Configure the main internal regulator output voltage
  */
  __HAL_RCC_PWR_CLK_ENABLE();
  __HAL_PWR_VOLTAGESCALING_CONFIG(PWR_REGULATOR_VOLTAGE_SCALE1);

  /** Initializes the RCC Oscillators according to the specified parameters
  * in the RCC_OscInitTypeDef structure.
  */
  RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_HSI;
  RCC_OscInitStruct.HSIState = RCC_HSI_ON;
  RCC_OscInitStruct.HSICalibrationValue = RCC_HSICALIBRATION_DEFAULT;
  RCC_OscInitStruct.PLL.PLLState = RCC_PLL_ON;
  RCC_OscInitStruct.PLL.PLLSource = RCC_PLLSOURCE_HSI;
  RCC_OscInitStruct.PLL.PLLM = 8;
  RCC_OscInitStruct.PLL.PLLN = 168;
  RCC_OscInitStruct.PLL.PLLP = RCC_PLLP_DIV2;
  RCC_OscInitStruct.PLL.PLLQ = 4;
  if (HAL_RCC_OscConfig(&RCC_OscInitStruct) != HAL_OK)
  {
    Error_Handler();
  }

  /** Initializes the CPU, AHB and APB buses clocks
  */
  RCC_ClkInitStruct.ClockType = RCC_CLOCKTYPE_HCLK|RCC_CLOCKTYPE_SYSCLK
                              |RCC_CLOCKTYPE_PCLK1|RCC_CLOCKTYPE_PCLK2;
  RCC_ClkInitStruct.SYSCLKSource = RCC_SYSCLKSOURCE_PLLCLK;
  RCC_ClkInitStruct.AHBCLKDivider = RCC_SYSCLK_DIV1;
  RCC_ClkInitStruct.APB1CLKDivider = RCC_HCLK_DIV4;
  RCC_ClkInitStruct.APB2CLKDivider = RCC_HCLK_DIV2;

  if (HAL_RCC_ClockConfig(&RCC_ClkInitStruct, FLASH_LATENCY_5) != HAL_OK)
  {
    Error_Handler();
  }
}

/* USER CODE BEGIN 4 */

/* USER CODE END 4 */

/**
  * @brief  This function is executed in case of error occurrence.
  * @retval None
  */
void Error_Handler(void)
{
  /* USER CODE BEGIN Error_Handler_Debug */
  /* User can add his own implementation to report the HAL error return state */
  __disable_irq();
  while (1)
  {
  }
  /* USER CODE END Error_Handler_Debug */
}
#ifdef USE_FULL_ASSERT
/**
  * @brief  Reports the name of the source file and the source line number
  *         where the assert_param error has occurred.
  * @param  file: pointer to the source file name
  * @param  line: assert_param error line source number
  * @retval None
  */
void assert_failed(uint8_t *file, uint32_t line)
{
  /* USER CODE BEGIN 6 */
  /* User can add his own implementation to report the file name and line number,
     ex: printf("Wrong parameters value: file %s on line %d\r\n", file, line) */
  /* USER CODE END 6 */
}
#endif /* USE_FULL_ASSERT */
